package com.sparkrico.ringtonepicker;

import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class RingtonePicker extends ListActivity implements OnClickListener{
	
	private static final String TAG = "RingtonePicker";
	private Uri mBaseUri;
	private Uri mSelectedUri;
	
	/** Whether this list has the 'Silent' item. */
    private boolean mHasSilentItem;
    
	/** Whether this list has the 'Default' item. */
    private boolean mHasDefaultItem;
    
    /** The Uri to play when the 'Default' item is clicked. */
    private Uri mUriForDefaultItem;
	
	private RingtoneManager mRingtoneManager;
	
	private long mSelectedId = 65535L;
	
	private ListView localListView;
	private SimpleCursorAdapter mCursorAdapter;
	
	private AdView adView;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        
        setContentView(R.layout.ringtonepicker);
        
        findViewById(R.id.ok).setOnClickListener(this);
        findViewById(R.id.cancel).setOnClickListener(this);
        
        setupAdmob();
        
        Intent intent = getIntent();
        
        mHasDefaultItem = intent.getBooleanExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
        mUriForDefaultItem = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI);
        if (mUriForDefaultItem == null) {
            mUriForDefaultItem = Settings.System.DEFAULT_RINGTONE_URI;
        }
        
        // Get whether to show the 'Silent' item
        mHasSilentItem = intent.getBooleanExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true);
        
        mSelectedUri = (Uri)intent.getParcelableExtra("android.intent.extra.ringtone.EXISTING_URI");
        mBaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        
        if(mSelectedUri!=null){
        	Log.d(TAG, mSelectedUri.toString());
        	try{
        		mSelectedId = ContentUris.parseId(mSelectedUri);
        	}catch (Exception e) {
        		e.printStackTrace();
			}
        }
        
        mRingtoneManager = new RingtoneManager(this);
    	
    	//
    	boolean includeDrm = intent.getBooleanExtra(RingtoneManager.EXTRA_RINGTONE_INCLUDE_DRM,
                true);
    	mRingtoneManager.setIncludeDrm(includeDrm);
    	//
    	int types = intent.getIntExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, -1);
        if (types != -1) {
            mRingtoneManager.setType(types);
        }
        
        localListView = getListView();
        localListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        
//      Media.INTERNAL_CONTENT_URI;
//      Media.EXTERNAL_CONTENT_URI;
        if(types == RingtoneManager.TYPE_RINGTONE){
	        //content://media/external/audio/media/83
	        setupExternalRingtone();
        }else{
	        //content://media/internal/audio/media/49
	        setupInternalRingtone();
        }
    }
    
    @Override
    protected void onDestroy() {
    	adView.destroy();
    	super.onDestroy();
    }
    
    private void setupAdmob(){
        adView = (AdView)this.findViewById(R.id.adView);
        adView.loadAd(new AdRequest());
    }
    
    private void setupExternalRingtone(){
    	Cursor cursor = getContentResolver().query(mBaseUri, null, null, null, null);
        while(cursor.moveToNext()){
        	
        	for (int i = 0; i < cursor.getColumnCount(); i++) {
        		if(!cursor.isNull(i))
        			Log.d(TAG, cursor.getColumnName(i) + " @ " + cursor.getString(i));
        		else
        			Log.d(TAG, cursor.getColumnName(i));
			}
        	break;
        }
        
        mCursorAdapter = new SimpleCursorAdapter(this, 
        		R.layout.simple, 
        		cursor, 
        		new String[]{MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA}, 
        		new int[]{R.id.radio, R.id.name, R.id.path});
        mCursorAdapter.setViewBinder(new ViewBinder() {
			
			public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
				if (columnIndex == 0){
					
					if(cursor.getLong(0)== mSelectedId){
						((RadioButton)view).setChecked(true);
					}else
						((RadioButton)view).setChecked(false);
					return true;
				}
				return false;
			}
		});
        
        localListView.setAdapter(mCursorAdapter);
//        localListView.setSaveEnabled(true);
        localListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mSelectedUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 
						id);
				localListView.setItemChecked(position, true);
				mSelectedId = id;
				
				getListView().invalidateViews();
			}
        	
		});
    }
    
    private void setupInternalRingtone(){
        
        Cursor cursor = mRingtoneManager.getCursor();
        while(cursor.moveToNext()){
        	for (int i = 0; i < cursor.getColumnCount(); i++) {
        		if(!cursor.isNull(i))
        			Log.d(TAG, cursor.getColumnName(i) + " @ " + cursor.getString(i));
        		else
        			Log.d(TAG, cursor.getColumnName(i));
			}
        	break;
        }
        
        mCursorAdapter = new SimpleCursorAdapter(this, 
        		R.layout.simple, 
        		cursor, 
        		new String[]{Media._ID, Media.TITLE, Media.TITLE_KEY}, 
        		new int[]{R.id.radio, R.id.name, R.id.path});
        mCursorAdapter.setViewBinder(new ViewBinder() {
			
			public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
				if (columnIndex == 0){
					if(cursor.getLong(0)== mSelectedId){
						((RadioButton)view).setChecked(true);
					}else
						((RadioButton)view).setChecked(false);
					return true;
				} else if (columnIndex == 3){
					view.setVisibility(View.GONE);
				}
				return false;
			}
		});
        
        localListView.setAdapter(mCursorAdapter);
        localListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mSelectedUri = ContentUris.withAppendedId(Media.INTERNAL_CONTENT_URI, 
						id);
				localListView.setItemChecked(position, true);
				mSelectedId = id;
				
				getListView().invalidateViews();
			}
        	
		});
    }
    
    @Override
    protected void onPause() {
    	// TODO Auto-generated method stub
    	super.onPause();
    }
    
    @Override
    protected void onRestart() {
    	// TODO Auto-generated method stub
    	super.onRestart();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	// TODO Auto-generated method stub
    	super.onSaveInstanceState(outState);
    }
    
    @Override
    protected void onStop() {
    	// TODO Auto-generated method stub
    	super.onStop();
    }

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ok:
			Intent localIntent1 = new Intent();
		    localIntent1.putExtra("android.intent.extra.ringtone.PICKED_URI", mSelectedUri);
		    setResult(RESULT_OK, localIntent1);
		    finish();
			break;
		case R.id.cancel:
			finish();
			break;

		default:
			break;
		}
	}
}